package main

import (
	"log"
	"net/http"
	"time"

	"gee"
)

/*
(1) global middleware Logger
$ curl http://localhost:9999/

(2) global + group middleware
$ curl http://localhost:9999/v2/hello/geektutu
*/

// https://geektutu.com/post/gee-day5.html
func main() {
	r := gee.New()

	/*注册中间件, 全局*/
	r.Use(gee.Logger())

	/*注册路由*/
	r.GET("/", funcName())
	r.Group("/v2").Use(v2middleware(), v2middleware2())
	r.Group("/v2").GET("/hello/:name", v2Function())

	/*监听*/
	if err := r.Run(":9999"); err != nil {
		return
	}
}

func funcName() func(c *gee.Context) {
	return func(c *gee.Context) {
		c.HTML(http.StatusOK, "<h1>Hello Gee</h1>")
	}
}

func v2middleware() func(c *gee.Context) {
	log.Printf("now binding v2middleware（注册的时候走一下，之后是直接拿HandlerFunc，相当于绑定的过程！！！）")
	return func(c *gee.Context) {
		/*		//Start timer
				t := time.Now()
				//if a server error occurred
				c.Fail(500, "Internal Server Error")*/
		log.Printf("中间件前序操作")

		c.Next()

		/*		// Calculate resolution time
				log.Printf("v2中间件：[%d] %s in %v for group v2", c.StatusCode, c.Req.RequestURI, time.Since(t))
		*/
		log.Printf("中间件后续操作")
	}
}

func v2middleware2() func(c *gee.Context) {
	log.Printf("now binding v2middleware2222（注册的时候走一下，之后是直接拿HandlerFunc，相当于绑定的过程！！！）")
	return func(c *gee.Context) {
		// Start timer
		t := time.Now()
		// if a server error occurred
		c.Fail(500, "Internal Server Error")
		// Calculate resolution time
		log.Printf("v2中间件：[%d] %s in %v for group v2", c.StatusCode, c.Req.RequestURI, time.Since(t))
	}
}

func v2Function() func(c *gee.Context) {
	log.Printf("now binding v2Function（注册的时候走一下，之后是直接拿HandlerFunc，相当于绑定的过程！！！）")
	return func(c *gee.Context) {
		log.Printf("now handle func")
		// expect /hello/geektutu
		c.String(http.StatusOK, "你好，%s，您在%s\n", c.Param("name"), c.Path)
	}
}
